package com.xja.dubbo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.xja.dubbo.entity.*;
import com.xja.dubbo.service.OrderService;
import com.xja.dubbo.service.ProductService;
import com.xja.dubbo.service.UserService;
import com.xja.dubbo.util.AlipayConfig;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ycz
 * @create 2021-12-20-19:44
 */
@Component
@RequestMapping("")
public class OrderController {

    @Reference(url = "dubbo://localhost:20883")
    private OrderService orderService;

    @Reference(url = "dubbo://localhost:20882")
    private UserService userService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductService productService;

    private Logger logger = LoggerFactory.getLogger(OrderController.class);

   @RequestMapping("addOrder")
    public void add(Easybuy_order order, @RequestParam("pids")List<Integer> pids, @CookieValue(required = false)String uuid, HttpServletResponse response,HttpServletRequest request){

       try {

           Easybuy_user loginUser = userService.findLoginUserFromRedis(uuid);


           //获取需要结算的订单商品
           List<Easybuy_order_detail> orderDetailList = new ArrayList<>();
           for (Integer pid : pids) {
               CarShop carShop = productService.findCarFromRedisByUidAndPid(loginUser.getId(), pid);
               Easybuy_order_detail orderDetail = new Easybuy_order_detail();
               orderDetail.setQuantity(carShop.getBuyNum());
               orderDetail.setProductid(carShop.getProduct().getId());
               orderDetail.setCost(carShop.getBuyNum()*carShop.getProduct().getPrice());
               orderDetailList.add(orderDetail);

           }
           order.setCreatetime(new Date());
           order.setUserid(loginUser.getId());
           int orderId = orderService.addOrder(order, orderDetailList);

          //如果是新地址，需要添加
           Easybuy_user_address address = new Easybuy_user_address();
           address.setAddress(order.getUseraddress());
           address.setUserid(loginUser.getId());
           userService.insertNewAddress(address);

           //删除购物车中需要结算的商品
           for (Integer pid : pids) {
               productService.deleteCarShopFromRedis(loginUser, pid);
           }



           //获得初始化的AlipayClient
           AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

           //设置请求参数
           AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
           alipayRequest.setReturnUrl(AlipayConfig.return_url);
           alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

           //商户订单号，商户网站订单系统中唯一订单号，必填
           String out_trade_no = orderId+"";
           //付款金额，必填
           String total_amount = order.getCost()+"";
           //订单名称，必填
           String subject = order.getLoginname()+"_"+order.getUseraddress();
           //商品描述，可空
           String body = "";

           alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                   + "\"total_amount\":\""+ total_amount +"\","
                   + "\"subject\":\""+ subject +"\","
                   + "\"body\":\""+ body +"\","
                   + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


           String form = "";
           try {
               form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
           } catch (AlipayApiException e) {
               e.printStackTrace();
           }
           response.setContentType("text/html;charset=" + AlipayConfig.charset);
           response.getWriter().write(form);// 直接将完整的表单html输出到页面
           response.getWriter().flush();
           response.getWriter().close();

       } catch (Exception e) {
           logger.error("添加订单失败", e);
       }

   }

   @RequestMapping("return")
    public String returnPage(HttpServletRequest request,HttpServletResponse response) throws IOException {

       try {

       Map<String,String> params = new HashMap<String,String>();
       Map<String,String[]> requestParams = request.getParameterMap();
       for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
           String name = (String) iter.next();
           String[] values = (String[]) requestParams.get(name);
           String valueStr = "";
           for (int i = 0; i < values.length; i++) {
               valueStr = (i == values.length - 1) ? valueStr + values[i]
                       : valueStr + values[i] + ",";
           }
           //乱码解决，这段代码在出现乱码时使用
           valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
           params.put(name, valueStr);
       }

       boolean signVerified = false; //调用SDK验证签名
       try {
           signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
       } catch (AlipayApiException e) {
           e.printStackTrace();
       }

       //——请在这里编写您的程序（以下代码仅作参考）——
       if(signVerified) {
           //商户订单号
           String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

           //支付宝交易号
           String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

           //付款金额
           String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");



           //跳转页面 支付成功 5秒自动到主页面
           request.setAttribute("out_trade_no",out_trade_no );
           request.setAttribute("trade_no", trade_no);
           request.setAttribute("total_amount", total_amount);


          orderService.updateOrderPayStatus(Integer.parseInt(out_trade_no), trade_no);

           return "BuyCar_Three";
       }else {
           response.getWriter().println("验证失败");
       }


    } catch (Exception e) {
           e.printStackTrace();
    }

       return "redirect:error.html";
   }


}
